package org.xjtu.weteam.web.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.xjtu.weteam.common.JsonResponse;
import org.xjtu.weteam.common.annotation.LogExecutionTime;
import org.xjtu.weteam.common.utils.SessionUtils;
import org.xjtu.weteam.model.domain.Team;
import org.xjtu.weteam.model.domain.User;
import org.xjtu.weteam.model.dto.LoginRequest;
import org.xjtu.weteam.model.dto.TeamDTO;
import org.xjtu.weteam.model.dto.UserDTO;
import org.xjtu.weteam.model.dto.UserInfoDTO;
import org.xjtu.weteam.service.UserService;

import java.io.File;


/**
 * @author Kevin
 */

@RestController
@RequestMapping("/api/user")
public class UserController {

    private final Logger logger = LoggerFactory.getLogger( UserController.class );

    @Autowired
    private UserService userService;

    // 这是个测试方法，在实际中不会这样用的，主要为了测试MVC三层架构
    @LogExecutionTime
    @PostMapping("/login")
    public JsonResponse login(@RequestBody LoginRequest loginRequest) {
        User user = userService.authenticate(loginRequest.getId(), loginRequest.getPassword());
        if (user != null) {
            SessionUtils.saveCurrentUser(user);
        }
//        return JsonResponse.successMessage("login success");
        return JsonResponse.success(user);
    }

    @PostMapping("/getUserId")
    public JsonResponse getUserId(@RequestBody String name){
        return JsonResponse.success(userService.getUserId(name));
    }

    @GetMapping("/getUserInfo")
    public JsonResponse getUserInfo(@RequestHeader("X-Access-Token") String token) {

        UserDTO userDTO = userService.getUserInfoByToken(token);

        return JsonResponse.success(userDTO);
    }

    @PostMapping("/setInfo")
    @ResponseBody
    public JsonResponse setInfo(UserInfoDTO userInfoDTO){
        try {
            String token = userInfoDTO.getToken();
            String userName = userInfoDTO.getUserName();
            String imagePath = userInfoDTO.getImagePath();
            userService.setUserInfoByToken(token,userName,imagePath);
            Thread.sleep(1000);
        } catch (Exception e) {
            return JsonResponse.success(false,"失败");
        }
        return JsonResponse.success(true,"已完成");
    }

}
